package com.lbj.mall.product.exception;

import com.lbj.mall.common.exception.AppException;
import com.lbj.mall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局处理Controller中的异常
 * RestControllerAdvice = ControllerAdvice + ResponseBody
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.lbj.mall.product.controller")
public class AppControllerAdvice {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handlerException(MethodArgumentNotValidException exception) {
        return R.error(AppException.VERIFY.getCode(),
                exception.getBindingResult().getFieldErrors().get(0).getDefaultMessage());
    }

    // ExceptionHandler(Throwable.class) 该方法可以处理哪些异常
    @ExceptionHandler(Throwable.class)
    public R handlerException(Throwable throwable) {
        log.error("Throwable --> {}", throwable.getMessage());
        return R.error(AppException.UNKNOWN.getCode(), AppException.UNKNOWN.getMsg());
    }
}
